/**
 * 
 */
package vin.echo.core.request;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;

import vin.echo.core.exception.ParamenterException;

/**
 * @author Vin.Ma
 * 
 */
public class Protocol {

	public static final String FUNCTION = "f_";

	public static final String QUERY = "q_";

	public static final String SESSION_KEY = "SESSION_KEY";

	public Map<String, String[]> querys;
	public EchoMehod method;
	
	@SuppressWarnings("unchecked")
	public Protocol(HttpServletRequest request,EchoMehod m) {
		querys=request.getParameterMap();
		this.method=m;
	}

	

	public String getFunction() throws ParamenterException {
		String[] func = querys.get(FUNCTION);
		if (func != null && func.length >= 1) {
			return func[0];
		}

		throw new ParamenterException();
	}

	public String getQuery() {
		switch (this.method) {
		case GET:
			return getQueryArg();
		case POST:
			return getPostArg();
		case PUT:
			return getPutArg();
		case DELETE:
			return getDeleteArg();
		default:
			return null;
		}
	}
	
	private String getDeleteArg() {
		// TODO Auto-generated method stub
		return null;
	}



	private String getPutArg() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 如果为get就简单的返回q_标示的第一个参数
	 * @return
	 */
	private String getQueryArg(){
		String[] query = querys.get(QUERY);
		if (query != null && query.length >= 1) {
		    return query[0];
		}
		return null;
	}
	
	/**
	 * 转化成post数组
	 * @return
	 */
	private String getPostArg(){
		Set<Entry<String, String[]>> entrySet = querys.entrySet();
		HashMap<String, String> mapArgs=new HashMap<String, String>();
		for(Entry<String, String[]> en:entrySet){
			//在这里拼成json
			String[] value = en.getValue();
			if(value!=null&&value.length==1){
				mapArgs.put(en.getKey(),value[0]);
			}
		}
		
		Gson gson=new Gson();
		return gson.toJson(mapArgs);
	}
}
